#pragma once
#include <string>
#include <stdint.h>
#include "base/core/com_define.h"
#include "DBOption/Mysql/MysqlConnector.h"

struct APPEND_CONTEXT 
{
    MysqlConnector* connector;
    char* writePos;
    int freeSize;
};

static inline bool AppendString(
								APPEND_CONTEXT *context,
								const char *prefixStringNotEscape,
								const std::string& stringNeedEscape,
								const char *postStringNotEscape
							   )
{
    bool result = false;
    bool retCode = false;
    uint32_t escapledLengh = 0;
    int length = 0;

    MMO_ASSERT(context && context->connector && context->writePos);

    if (prefixStringNotEscape) 
	{
        length = (int)strlen(prefixStringNotEscape);
        MMOLOG_ASSERT_EXIT(context->freeSize > length);
        memcpy(context->writePos, prefixStringNotEscape, length);
        context->writePos += length;
        context->freeSize -= length;
    }

    length = (int)stringNeedEscape.length();
    MMOLOG_ASSERT_EXIT(context->freeSize > (length * 2 + 1));

    retCode = context->connector->EscapeString(context->writePos, stringNeedEscape.c_str(), length, escapledLengh);
    MMOLOG_ASSERT_EXIT(retCode);
    context->writePos += escapledLengh;
    context->freeSize -= escapledLengh;

    if (postStringNotEscape) 
	{
        length = (int)strlen(postStringNotEscape);
        MMOLOG_ASSERT_EXIT(context->freeSize > length);
        memcpy(context->writePos, postStringNotEscape, length);
        context->writePos += length;
        context->freeSize -= length;
    }

    result = true;
Exit0:
    return result;
}

static inline bool AppendString(
								APPEND_CONTEXT *context,
								const std::string& stringNeedEscape,
								const char *postStringNotEscape
							   ) 
{
    bool result = false;
    bool retCode = false;
    uint32_t escapledLengh = 0;
    int length = 0;

    MMO_ASSERT(context && context->connector && context->writePos);

    length = (int)stringNeedEscape.length();
    MMOLOG_ASSERT_EXIT(context->freeSize > (length * 2 + 1));

    retCode = context->connector->EscapeString(
        context->writePos, stringNeedEscape.c_str(), length, escapledLengh
        );
    MMOLOG_ASSERT_EXIT(escapledLengh <= (uint32_t)(length * 2 + 1));
    MMOLOG_ASSERT_EXIT(retCode);
    context->writePos += escapledLengh;
    context->freeSize -= escapledLengh;

    if (postStringNotEscape) {
        length = (int)strlen(postStringNotEscape);
        MMOLOG_ASSERT_EXIT(context->freeSize > length);
        memcpy(context->writePos, postStringNotEscape, length);
        context->writePos += length;
        context->freeSize -= length;
    }

    result = true;
Exit0:
    return result;
}